<!--
 * @Author: zulezhe
 * @Date: 2021-01-26 14:02:01
 * @LastEditors: zulezhe
 * @LastEditTime: 2021-01-26 14:02:11
 * @Description: In User Settings Edit
 * @FilePath: \canvas\02-进阶\百分比圆圈.html
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <canvas id="canvas" width="500" height="400" style="background: #ccc"></canvas>
    <script>
      let canvas = document.getElementById("canvas"),
        context = canvas.getContext("2d"),
        centerX = canvas.width / 2,
        centerY = canvas.height / 2,
        rad = (Math.PI * 2) / 100, // Math.PI * 2 一个圆的弧度分成100份
        speed = 0.1;

      // 圆圈百分比
      function blurCircle(n) {
        context.save();
        context.beginPath();
        context.strokeStyle = "#49f";
        context.lineWidth = 12;
        context.arc(centerX, centerY, 100, -Math.PI / 2, -Math.PI / 2 + n * rad, false);
        context.stroke();
        context.restore();
      }

      // 圆圈底色
      function whiteCircle() {
        context.save();
        context.beginPath();
        context.strokeStyle = "#a5def1";
        context.lineWidth = 12;
        context.arc(centerX, centerY, 100, 0, Math.PI * 2, false);
        context.stroke();
        context.closePath();
        context.restore();
      }

      // 文字
      function drawText(n) {
        context.save();
        context.fillStyle = "#f47c7c";
        context.font = "40px Arial";
        context.textAlign = "center";
        context.textBaseLine = "middle";
        context.fillText(n.toFixed(0) + "%", centerX, centerY);
        context.restore();
      }

      // 循环
      (function drawFrame() {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);

        whiteCircle();
        drawText(speed);
        blurCircle(speed);
        if (speed > 100) speed = 0;
        speed += 0.1;
      })();
    </script>
  </body>
</html>
